package com.jkoa.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import java.util.List;
import org.antlr.stringtemplate.StringTemplate;
import org.apache.log4j.Logger;
import org.xhtmlrenderer.pdf.ITextRenderer;


/**
 *
 * @author fikri
 */
public class ReportService {


    DecimalFormat df = new DecimalFormat("#,###,##0.00");

    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aaa");
    
    private static Logger LOG = Logger.getLogger(ReportService.class);


    

    public String cetakLaporan (String laporan, List obj) {
         try {

            String report = readAsString(ReportService.class.getResourceAsStream("/com/jkoa/report/" + laporan + ".st"));
            StringTemplate template = new StringTemplate(report);
            
            template.setAttribute("paramList", obj);            

            report = template.toString();
            
            return generateReport(report);
        } catch (Exception ex) {
            LOG.error(ex);
        }
        return null;
        
    }


    private static String generateReport(String report) throws Exception {
        //System.out.println("report gen");
        //System.out.println(report);
        String tmp = System.getProperty("java.io.tmpdir");
        File tmpdir = new File(tmp);
        File dir = new File(tmpdir, "generated_report_dir/");
        if (!dir.exists()) {
            dir.mkdir();
        }        

        File rpt = File.createTempFile("rpt" + System.currentTimeMillis(), ".html", dir);
        rpt.deleteOnExit();
        report = new String(report.getBytes("utf8"));
        writeAsString(rpt, report);
        File pdf = File.createTempFile("rptGen" + System.currentTimeMillis(), ".pdf", dir);
        pdf.deleteOnExit();
        OutputStream os = new FileOutputStream(pdf);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(rpt.toURI().toURL().toString());
        renderer.layout();
        renderer.createPDF(os);
        renderer.finishPDF();
        os.close();
        return pdf.getCanonicalPath();
    }

     public static String readAsString(InputStream is) {
        StringBuilder b = new StringBuilder();
        try {
            BufferedReader r = new BufferedReader(new InputStreamReader(is));
            while (true) {
                int ch;
                ch = r.read();
                if (ch == -1) {
                    break;
                }
                b.append((char) ch);
            }
            r.close();
        } catch (IOException ex) {
            LOG.error(ex);
        }
        return b.toString();
    }

    public static String writeAsString(File file, String contents) {
        Writer out = null;
        try {
            File parentDir = file.getParentFile();
            if (!parentDir.exists() && !parentDir.mkdirs()) {
                return "unable to make parent dir for " + file;
            }
            Reader in = new StringReader(contents);
            out = new FileWriter(file);
            copyStream(in, out);
            return null;
        } catch (IOException e) {
            return "[FileUtil] ERROR writing file : " + e.getMessage();
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                } // ignored

            }
        }
    }

    public static void copyStream(InputStream in, OutputStream out) throws IOException {
        final int MAX = 4096;
        byte[] buf = new byte[MAX];
        for (int bytesRead = in.read(buf, 0, MAX);
                bytesRead != -1;
                bytesRead = in.read(buf, 0, MAX)) {
            out.write(buf, 0, bytesRead);
        }
    }

    public static void copyStream(Reader in, Writer out) throws IOException {
        final int MAX = 4096;
        char[] buf = new char[MAX];
        for (int bytesRead = in.read(buf, 0, MAX);
                bytesRead != -1;
                bytesRead = in.read(buf, 0, MAX)) {
            out.write(buf, 0, bytesRead);
        }
    }

    public static void writeAsByte(File file, byte[] b) throws Exception {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(b);
        fos.close();
    }


}
